package com.story.modular.app.controller.radio;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.story.common.annotion.BussinessLog;
import com.story.common.constant.Dict;
import com.story.common.constant.factory.PageFactory;
import com.story.common.exception.BizExceptionEnum;
import com.story.common.exception.BussinessException;
import com.story.common.persistence.dao.BannerMapper;
import com.story.common.persistence.dao.RecommendLocationMapper;
import com.story.common.persistence.dao.RecommendMapper;
import com.story.common.persistence.dao.VedioCategoryMapper;
import com.story.common.persistence.model.Banner;
import com.story.common.persistence.model.Recommend;
import com.story.common.persistence.model.RecommendLocation;
import com.story.common.persistence.model.VedioCategory;
import com.story.config.properties.UpyunProperties;
import com.story.core.base.controller.BaseController;
import com.story.core.util.ToolUtil;
import com.story.core.util.UriUtil;
import com.story.modular.app.dao.RecommendDao;
import com.story.modular.app.dao.VedioCategoryDao;
import com.story.modular.app.service.UpyunService;
import com.story.modular.app.transfer.RecAddDto;
import com.story.modular.app.warpper.RecommendWarpper;
import main.java.com.upyun.UpException;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangbo
 * @date 2019-07-12 10:18
 */
@Controller
@RequestMapping(value = "/rec/radio")
public class RadioRecommendController extends BaseController {

    private static final String PREFIX = "/app/recommend/radio/";

    private static final Long EXPIRE_TIME = 3600L;

    @Autowired
    private RecommendDao recommendDao;

    @Autowired
    private UpyunProperties upyunProperties;

    @Autowired
    private RecommendMapper recommendMapper;

    @Autowired
    private BannerMapper bannerMapper;

    @Autowired
    private VedioCategoryMapper vedioCategoryMapper;

    @Autowired
    private VedioCategoryDao vedioCategoryDao;

    @Autowired
    private RecommendLocationMapper recommendLocationMapper;

    @Autowired
    private UpyunService upyunService;

    /**
     * 首页
     * @return
     */
    @GetMapping(value = "")
    public String index() {
        return PREFIX + "recommend.html";
    }

    /**
     * 列表
     * @param keyword
     * @param beginTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object recList(@RequestParam(value = "keyword",required = false) String keyword,
                          @RequestParam(value = "beginTime",required = false) String beginTime,
                          @RequestParam(value = "endTime",required = false) String endTime) {
        Page<Recommend> page = new PageFactory<Recommend>().defaultPage();
        List<Map<String,Object>> recommendList = recommendDao.recListByConditions(page,keyword.trim(),
                beginTime,endTime,page.getOrderByField(),page.isAsc(),0);
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>(recommendList.size());
        for (Map map : recommendList) {
            map.put("picPath",upyunProperties.getDomain() + map.get("picPath"));
            result.add(map);
        }
        page.setRecords((List<Recommend>) new RecommendWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 删除推荐
     * @param recIds
     * @return
     */
    @BussinessLog(value = "删除推荐", key = "id", dict = Dict.DeleteDict)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object deleteVedio(@RequestParam(value = "recIds") String recIds) {
        String[] recIdStr = recIds.split(",");
        List<Integer> recIdList = new ArrayList<>();
        for (String recId : recIdStr) {
            recIdList.add(Integer.valueOf(recId));
        }
        //删除本身即可
        for (Integer id : recIdList) {
            recommendMapper.deleteById(id);
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 进入新增页
     * @param model
     * @return
     */
    @RequestMapping(value = "/recAdd")
    public String toAddPage(Model model) {
        //banner信息
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<String,Object>(16);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        //cate信息
        //查询所有专辑
        List<Map<String,Object>> categoryList = vedioCategoryDao.getAllCategory(0);
        if(categoryList.isEmpty()) {
            throw new BussinessException( BizExceptionEnum.CATES_NULL);
        }
        //推荐位模板信息
        List<RecommendLocation> recommendLocations = recommendLocationMapper
                .selectList(new EntityWrapper<RecommendLocation>().eq("templateId",0));
        List<Map<String,Object>> locationList = new ArrayList<>(recommendLocations.size());
        for (RecommendLocation location : recommendLocations) {
            Map<String,Object> map = new HashMap<>(6);
            map.put("id",location.getId());
            map.put("title",location.getTitle());
            locationList.add(map);
        }

        //写入modal中
        model.addAttribute("bannerList",bannerList);
        model.addAttribute("cateList",categoryList);
        model.addAttribute("locationList",locationList);

        //返回页面
        return PREFIX + "recommend_add.html";
    }

    /**
     * 一个栏目下的专辑
     * @param bannerId
     * @return
     */
    @RequestMapping(value = "/cateInBanner")
    @ResponseBody
    public List<Map<String,Object>> cateInBanner(@RequestParam(value = "bannerId") Integer bannerId) {
        bannerId = bannerId == 0 ? null : bannerId;
        List<Map<String,Object>> categoryList = vedioCategoryDao.getCateInBanner(bannerId,0);
        return categoryList;
    }

    /**
     * 新增一个推荐
     * @param recAddDto
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object addRec(RecAddDto recAddDto) throws IOException, UpException {
        if(ToolUtil.isOneEmpty(recAddDto,recAddDto.getLogoPath(),recAddDto.getCateList(),recAddDto.getRecList(),recAddDto.getRecTitle())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        //检查数据库中推荐位是否已被其它推荐占用
        Integer locationId = recAddDto.getRecList();
        List<Recommend> recommends = recommendMapper.selectList(new EntityWrapper<Recommend>().eq("locationId",recAddDto.getRecList()));
        if(recommends!= null && recommends.size() != 0) {
            throw new BussinessException(BizExceptionEnum.REC_EXIST);
        }
        String cateIds = recAddDto.getCateList();
        List<Integer> cateIdInts = new ArrayList<>();
        if(!cateIds.contains(",")) {
             cateIdInts.add(Integer.valueOf(cateIds));
        } else {
            String[] cateIdArr = cateIds.split(",");
            for (String cateIdStr : cateIdArr) {
                cateIdInts.add(Integer.valueOf(cateIdStr));
            }
        }
        Recommend recommend = new Recommend();
        recommend.setCateId(cateIdInts.get(0));
        recommend.setLocationId(locationId);
        recommend.setPicPath(getUrl(recAddDto.getLogoPath(),"logo"));
        recommend.setTitle(recAddDto.getRecTitle());
        recommendMapper.insert(recommend);
        return super.SUCCESS_TIP;
    }

    /**
     * 进入修改页面
     * @param recId
     * @param model
     * @return
     */
    @RequestMapping(value = "/recUpdate/{recId}")
    public String toUpdatePage(@PathVariable Integer recId,Model model) {
        //栏目
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<String,Object>(8);
            map.put("name",banner.getName());
            map.put("id",banner.getId());
            bannerMapList.add(map);
        }
        //推荐详细信息
        Map<String,Object> recommend = recommendDao.recommendDetailById(recId);
        recommend.put("picPath",upyunProperties.getDomain() + recommend.get("picPath"));
        //得到所有的location
        List<RecommendLocation> recommendLocations = recommendLocationMapper
                .selectList(new EntityWrapper<RecommendLocation>().eq("templateId",0));
        List<Map<String,Object>> locationMapList = new ArrayList<>(recommendLocations.size());
        for (RecommendLocation location : recommendLocations) {
            Map<String,Object> map = new HashedMap(8);
            map.put("id",location.getId());
            map.put("title",location.getTitle());
            if(recommend.get("locationId").equals(location.getId())) {
                map.put("selected","selected");
            }
            locationMapList.add(map);
        }
        recommend.remove("locationId");
        recommend.put("locations",locationMapList);
        //得到所有的专辑
        List<VedioCategory> categoryList = vedioCategoryMapper.selectList(new EntityWrapper<VedioCategory>().eq("resType",0));
        List<Map<String,Object>> categoryMapList = new ArrayList<>(categoryList.size());
        for (VedioCategory category : categoryList) {
            Map<String,Object> map = new HashMap<>(8);
            map.put("id",category.getId());
            map.put("name",category.getName());
            if(category.getId().equals(recommend.get("cateId"))) {
                map.put("checked","checked");
                recommend.put("cateName",category.getName());
            }
            categoryMapList.add(map);
        }

        recommend.remove("cateId");
        recommend.put("categorys",categoryMapList);

        //添加数据到model中
        model.addAttribute("bannerList",bannerList);
        model.addAttribute("recommend",recommend);
        return PREFIX + "recommend_update.html";
    }

    /**
     * 修改数据
     * @param recAddDto
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(RecAddDto recAddDto) throws IOException, UpException {
        //参数校验
        if(ToolUtil.isOneEmpty(recAddDto,recAddDto.getId(),recAddDto.getCateList(),recAddDto.getLogoPath(),recAddDto.getRecList(),recAddDto.getRecTitle())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String cateIds = recAddDto.getCateList();
        List<Integer> cateIdInts = new ArrayList<>();
        if(!cateIds.contains(",")) {
            cateIdInts.add(Integer.valueOf(cateIds));
        } else {
            String[] cateIdArr = cateIds.split(",");
            for (String cateIdStr : cateIdArr) {
                Integer cateIdInt = Integer.valueOf(cateIdStr);
                cateIdInts.add(cateIdInt);
            }
        }
        //查询出原位置，看推荐位是否发生改变
        Recommend recommend = recommendMapper.selectById(recAddDto.getId());
        if(recommend.getLocationId().equals(recAddDto.getRecList())) {
            //相同则直接提交
            Recommend willSaveRec = new Recommend();
            willSaveRec.setTitle(recAddDto.getRecTitle());
            willSaveRec.setId(recAddDto.getId());
            willSaveRec.setPicPath(this.getUrl(recAddDto.getLogoPath(),"logo"));
            willSaveRec.setCateId(cateIdInts.get(0));
            willSaveRec.setLocationId(recAddDto.getRecList());
            recommendMapper.updateById(willSaveRec);
        } else {
            //不同则将原来的location换成现在的
            Recommend query = new Recommend();
            query.setLocationId(recAddDto.getRecList());
            Recommend willUpdateRec = recommendMapper.selectOne(query);
            willUpdateRec.setLocationId(recommend.getLocationId());
            recommendMapper.updateById(willUpdateRec);
            Recommend willSaveRec = new Recommend();
            willSaveRec.setId(recAddDto.getId());
            willSaveRec.setTitle(recAddDto.getRecTitle());
            willSaveRec.setPicPath(this.getUrl(recAddDto.getLogoPath(),"logo"));
            willSaveRec.setCateId(cateIdInts.get(0));
            willSaveRec.setLocationId(recAddDto.getRecList());
            recommendMapper.updateById(willSaveRec);
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 处理连接
     * @param fontUrl
     * @param type
     * @return
     * @throws IOException
     * @throws UpException
     */
    private String getUrl(String fontUrl,String type) throws IOException, UpException {
        if(fontUrl.contains("?")) {
            fontUrl = fontUrl.split("\\?")[0];
        }
        if(!fontUrl.contains(upyunProperties.getDomain())) {
            if(fontUrl.startsWith("/")) {
                if(upyunService.getFileInfo(fontUrl) == null) {
                    if("logo".equals(type)) {
                        throw new BussinessException( BizExceptionEnum.LOGO_ADDRESS_ERROR);
                    }
                }
            } else {
                if(upyunService.getFileInfo("/" + fontUrl) == null) {
                    if("logo".equals(type)) {
                        throw new BussinessException( BizExceptionEnum.LOGO_ADDRESS_ERROR);
                    }
                }
                fontUrl = "/" + fontUrl;
            }
        } else {
            if(upyunService.getFileInfo( UriUtil.getUri(fontUrl)) == null) {
                if("logo".equals(type)) {
                    throw new BussinessException( BizExceptionEnum.LOGO_ADDRESS_ERROR);
                }
            }
            fontUrl = UriUtil.getUri(fontUrl);
        }
        return fontUrl;
    }
}
